package com.xb.p41_touchdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    TestView testView;

    VelocityTracker tracker;        //速率追踪器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        testView=findViewById(R.id.my_testView);
        testView.setOnTouchListener(new myTouch());
    }

    //触摸事件监听
    private class myTouch implements View.OnTouchListener{
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            //获取触摸事件的坐标
            float x1,y1;
            x1 = event.getX();
            y1 = event.getY();

            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    testView.setXY(x1,y1);
                    testView.invalidate();//刷新界面
                    if(tracker==null){
                        tracker=VelocityTracker.obtain();
                    }else {
                        tracker.clear();
                    }
                    tracker.addMovement(event);//按下时，将动作事件添加到运动监视器，从而时刻监视运动行为
                    break;
                case MotionEvent.ACTION_MOVE:
                    testView.setXY(x1,y1);
                    testView.invalidate();//刷新界面
                    //实时的计算运动速度
                    tracker.addMovement(event);
                    tracker.computeCurrentVelocity(1000);//多长时间内的速率
                    Toast.makeText(getApplicationContext(),"Velocity(单位是：像素/秒):x的速率="+tracker.getXVelocity()+",y的速率="+tracker.getYVelocity(),Toast.LENGTH_SHORT).show();
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    //手势抬起的时候，将监视器对象取消
                    if(tracker!=null){
                        tracker.recycle();
                        tracker=null;
                    }
                    break;
            }
            return true;
        }
    }
}